package a.server;
/**
 * Author:20201002983郑雨蓓
 * Date: 2022/12/3
 * Description:
 */

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Register {
  private ConnectionProvider provider;
  private Connection con = null;
  private PreparedStatement stmt = null;
  private ResultSet rs = null;

  public Register(ConnectionProvider provider) {
    this.provider = provider;
  }

  public Integer addUsers(String username, String password) {
    if (isUserExist(username)) {
      return -1;
      //用户名已存在，应该是密码错误
    }
    try {
      con = this.provider.getConnection();
      String sql = "insert into users(username,password) values(?,?)";
      stmt = con.prepareStatement(sql);
      stmt.setObject(1, username);
      stmt.setObject(2, password);
      return stmt.executeUpdate();//返回影响的行数
    } catch (SQLException e) {
      e.printStackTrace();
      return 0;
    } finally {
      try {
        if (stmt != null) stmt.close();
        if (con != null) con.close();
      } catch (SQLException e) {
      }
    }
  }//addUsers

  public boolean login(String username, String password) {
    try {
      con = provider.getConnection();
      String sql = "SELECT username,password from users where username=? and password=?";
      stmt = con.prepareStatement(sql);
      stmt.setObject(1, username);
      stmt.setObject(2, password);
      rs = stmt.executeQuery();
      return rs.next();//返回是否有数据
    } catch (SQLException e) {
      e.printStackTrace();
      return false;
    }

  }

  public boolean isUserExist(String username) {
    try {
      con = provider.getConnection();
      String sql = "SELECT username from users where username=? ";
      stmt = con.prepareStatement(sql);
      stmt.setObject(1, username);
      rs = stmt.executeQuery();
      return rs.next();//返回是否有数据
    } catch (SQLException e) {
      e.printStackTrace();
      return false;
    }
  }

  public void printAllUsers() {
    try {
      con = provider.getConnection();
      String sql = "SELECT id,username,password from users";
      stmt = con.prepareStatement(sql);
      rs = stmt.executeQuery();
      //输出查询结果
      while (rs.next()) {
        System.out.print(rs.getString(1) + "\t");
        System.out.print(rs.getString(2) + "\t");
        System.out.print(rs.getString(3) + "\t");
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (con != null) con.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }


}
